package com.me.screen;

import java.util.Iterator;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import com.me.MyAppleDrop.MainAppleDrop;
import com.me.constant.Constant;
import com.me.control.CreateWindown;

public class PlayScreen extends BaseScreen {

	Sound dropSound;
	Music rainMusic;
	OrthographicCamera camera;
	Rectangle bucket;
	Array<Rectangle> greenAppledrops;
	Array<Rectangle> redAppledrops;
	Array<Rectangle> wormDrops;
	long lastDropTime;
	Image img_greenApple;
	Image img_redApple;
	Image img_bg;
	Image img_worm;
	Image bucketImage;
	Label lb_score;
	Label lb_time;
	CreateWindown createWindow;
	@Override
	public void show() {
		super.show();

		Constant.iTimePlay = 60;
		Constant.iScore = 0;
		// load the images for the droplet and the bucket, 64x64 pixels each
		img_bg = new Image(MainAppleDrop.getAtlas().findRegion("datagame/MenuBg"));
		
		bucketImage = new Image(MainAppleDrop.getAtlas().findRegion(
				"datagame/bucket"));
		img_greenApple = new Image(MainAppleDrop.getAtlas().findRegion(
				"datagame/greenApple"));
		img_redApple = new Image(MainAppleDrop.getAtlas().findRegion(
				"datagame/redApple"));
		img_worm = new Image(MainAppleDrop.getAtlas().findRegion(
				"datagame/icon-cai-dat"));
		// load the drop sound effect and the rain background "music"
		dropSound = Gdx.audio.newSound(Gdx.files.internal("music/drop.wav"));
		rainMusic = Gdx.audio.newMusic(Gdx.files.internal("music/rain.mp3"));

		// start the playback of the background music immediately
		rainMusic.setLooping(true);
		rainMusic.play();

		// create the camera and the SpriteBatch
		camera = new OrthographicCamera();
		camera.setToOrtho(false, 800, 480);

		// create a Rectangle to logically represent the bucket
		bucket = new Rectangle();
		bucket.x = 800 / 2 - 64 / 2; // center the bucket horizontally
		bucket.y = 10; // bottom left corner of the bucket is 20 pixels above
						// the bottom screen edge
		bucket.width = 64;
		bucket.height = 64;
		// create the Appledrops array and spawn the first raindrop
		greenAppledrops = new Array<Rectangle>();
		redAppledrops = new Array<Rectangle>();
		wormDrops = new Array<Rectangle>();

		spawnRaindrop();
		lb_score = new Label("Score: "+ Constant.iScore, MainAppleDrop.getMySkin(),"label24_bold");
		lb_score.setX(Constant.STAGE_WIDTH - lb_score.getWidth() - 40);
		lb_score.setY(Constant.STAGE_HEIGHT - lb_score.getHeight() - 10);
		
		lb_time = new Label("Time: " + Constant.iTimePlay, MainAppleDrop.getMySkin(), "label24_bold");
		lb_time.setX(10);
		lb_time.setY(lb_score.getY());
	}

	private void spawnRaindrop() {
		Rectangle greenAppledrop = new Rectangle();
		greenAppledrop.x = MathUtils.random(0, 800 - 64);
		greenAppledrop.y = 480;
		greenAppledrop.width = 64;
		greenAppledrop.height = 64;
		greenAppledrops.add(greenAppledrop);

		Rectangle redAppleDrop = new Rectangle();
		redAppleDrop.x = MathUtils.random(5, 800 - 48);
		redAppleDrop.y = 480;
		redAppleDrop.width = 48;
		redAppleDrop.height = 48;
		redAppledrops.add(redAppleDrop);

		Rectangle wormDrop = new Rectangle();
		wormDrop.x = MathUtils.random(15, 800 - 48);
		wormDrop.y = 480;
		wormDrop.width = 52;
		wormDrop.height = 52;
		wormDrops.add(wormDrop);

		lastDropTime = TimeUtils.nanoTime();
	}

	public static boolean b_check = true;
	@Override
	public void render(float arg0) {
		super.render(arg0);
		// clear the screen with a dark blue color.
		// The arguments to glClearColor are the red, green blue and alpha
		// component in the range [0,1] of the color to be used to clear thescreen.
		if(b_check){
			Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
			
			// tell the camera to update its matrices.
			camera.update();
			//Time to play game
			Constant.fTimeDelta += Gdx.graphics.getDeltaTime();
			if (Constant.fTimeDelta >= 1) {
				Constant.iTimePlay -= 1;
				lb_time.setText("Time: "+ Constant.iTimePlay);
				Constant.fTimeDelta = 0;
			}
			// begin a new batch and draw the bucket and all drops
			bucketImage.setX(bucket.x);
			bucketImage.setY(bucket.y);
			stage.addActor(bucketImage);
	
			for (Rectangle greenAppledrop : greenAppledrops) {
				img_greenApple.setX(greenAppledrop.x);
				img_greenApple.setY(greenAppledrop.y);
				stage.addActor(img_greenApple);
				stage.act();
				stage.draw();
			}
	
			for (Rectangle redAppleDrop : redAppledrops) {
				img_redApple.setX(redAppleDrop.x);
				img_redApple.setY(redAppleDrop.y);
				stage.addActor(img_redApple);
				stage.act();
				stage.draw();
			}
	
			for (Rectangle wormDrop : wormDrops) {
				img_worm.setX(wormDrop.x);
				img_worm.setY(wormDrop.y);
				stage.addActor(img_worm);
				stage.act();
				stage.draw();
			}
	
			// process user input
			if (Gdx.input.isTouched()) {
				Vector3 touchPos = new Vector3();
				touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
				camera.unproject(touchPos);
				bucket.x = touchPos.x - 64 / 2;
			}
	
			if (Gdx.input.isKeyPressed(Keys.LEFT))
				bucket.x -= 200 * Gdx.graphics.getDeltaTime();
			if (Gdx.input.isKeyPressed(Keys.RIGHT))
				bucket.x += 200 * Gdx.graphics.getDeltaTime();
	
			// make sure the bucket stays within the screen bounds
			if (bucket.x < 0)
				bucket.x = 0;
			if (bucket.x > 800 - 64)
				bucket.x = 800 - 64;
	
			// check if we need to create a new raindrop
			if (TimeUtils.nanoTime() - lastDropTime > 1000000000)
				spawnRaindrop();
	
			// move the raindrops, remove any that are beneath the bottom edge of
			// the screen or that hit the bucket. In the later case we play back
			// a sound effect as well.
			Iterator<Rectangle> iter = greenAppledrops.iterator();
			while (iter.hasNext()) {
				Rectangle greenAppledrop = iter.next();
				greenAppledrop.y -= 250 * Gdx.graphics.getDeltaTime();
				if (greenAppledrop.y + 64 < 0)
					iter.remove();
				if (greenAppledrop.overlaps(bucket)) {
					dropSound.play();
					iter.remove();
					Constant.iScore += 1;
					lb_score.setText("Score:  " + Constant.iScore);
				}
			}
	
			Iterator<Rectangle> iterRed = redAppledrops.iterator();
			while (iterRed.hasNext()) {
				Rectangle redAppledrop = iterRed.next();
				redAppledrop.y -= 300 * Gdx.graphics.getDeltaTime();
				if (redAppledrop.y + 48 < 0)
					iterRed.remove();
				if (redAppledrop.overlaps(bucket)) {
					dropSound.play();
					iterRed.remove();
					Constant.iScore += 2;
					lb_score.setText("Score:  " + Constant.iScore);
				}
			}
	
			Iterator<Rectangle> iterWorm = wormDrops.iterator();
			while (iterWorm.hasNext()) {
				Rectangle wormDrop = iterWorm.next();
				wormDrop.y -= 200 * Gdx.graphics.getDeltaTime();
				if (wormDrop.y + 52 < 0)
					iterWorm.remove();
				if (wormDrop.overlaps(bucket)) {
					dropSound.play();
					iterWorm.remove();
					Constant.iScore -= 2;
					lb_score.setText("Score:  " + Constant.iScore);
				}
			}
			
			stage.addActor(lb_time);
			stage.addActor(lb_score);
			
			//Check lose game
			checkEndGame();
		}
	}

	@Override
	public void dispose() {
		super.dispose();
	}

	private void checkEndGame(){
		if(Constant.iTimePlay == 0 || Constant.iScore < 0){
			b_check = false;
			Gdx.graphics.setContinuousRendering(false);
			Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
			createWindow = new CreateWindown();
			stage.addActor(createWindow.img_backgroundHide);
			stage.addActor(createWindow.CreateWindow_LoseGame());
			stage.addActor(lb_score);
			stage.addActor(lb_time);
			rainMusic.stop();
			stage.act(GL10.GL_COLOR_BUFFER_BIT);
			stage.draw();
		}
	}
}
